package handlers

import (
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/gin-knife/consts"
	"github.com/gin-gonic/gin"
	"github.com/juju/errors"
	"github.com/loopfz/gadgeto/tonic"
)

type GreetUserInput struct {
	// path 指定从路径参数中获取值，其他方式：path/query/body/header，默认body
	Name string `path:"name" description:"User name" validate:"required"`
}

type GreetUserOutput struct {
	Message string `json:"message"`
}

/*
这里不用再写gin原生的 func(c *gin.Context) {} 了,直接写tonic定义的handler，handler形式如下：
func(*gin.Context, [input object ptr]) ([output object], error){}
其中 方括号的 是可选参数，默认请求方式是 application/json .
入参会自动装配
*/

// GreetUser 业务逻辑
func GreetUser(c *gin.Context, in *GreetUserInput) (*GreetUserOutput, error) {
	fmt.Printf("--------in---%+v \n", in)
	userId, exist := c.Get(consts.USER_ID)
	if exist {
		fmt.Printf("--------userId---%s \n", userId)

	}

	if in.Name == "satan" {
		// 这里返回错误会进入全局错误逻辑ErrorHook
		return nil, errors.NewForbidden(nil, "go to hell")
	}

	// 这里返回会进入RenderHook
	return &GreetUserOutput{Message: fmt.Sprintf("Hello %s!", in.Name)}, nil
}

func addGreet(root *gin.Engine) {
	root.GET("/hello/:name", tonic.Handler(GreetUser, 200))

}
